﻿using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.Logging;
using PLCS.Application.Contracts.MenuApp;
using PLCS.Application.Contracts.MenuApp.Dtos;
using PLCS.Domain.Menus;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.MenuApp;

public class MenuAppService : ApplicationService, IMenuAppService
{
    private readonly IRepository<Menu> _repository;

    public MenuAppService(IRepository<Menu> repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 创建菜单
    /// </summary>
    /// <param name="menuEditDto"></param>
    /// <returns></returns>
    public async Task CreateAsync(MenuEditDto menuEditDto)
    {
        // 一级菜单
        if (string.IsNullOrEmpty(menuEditDto.ViewName))
            await _repository.InsertAsync(new Menu(menuEditDto.Title, (PackIconKind)menuEditDto.Icon));

        // 二级菜单
        else
        {
            var menu = await _repository.GetAsync(x => x.Title == menuEditDto.ParentTitle);
            Guid ParentId = menu.Id;
            await _repository.InsertAsync(new Menu(menuEditDto.Title, menuEditDto.ViewName, ParentId));
        }
    }

    /// <summary>
    /// 根据ID删除菜单
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task DeleteAsync(Guid Id)
    {
        var todeleteMenus = new List<Menu>();
        var menu = await _repository.GetAsync(x => x.Id == Id);
        menu.Children = await _repository.GetListAsync(x => x.Parent == menu);
        todeleteMenus.Add(menu);
        if (menu.Children != null && menu.Children.Count > 0)
        {
            todeleteMenus.AddRange(menu.Children);
        }
        await _repository.DeleteManyAsync(todeleteMenus);
    }

    /// <summary>
    /// 获取所有菜单
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<MenuDto>> GetListAsync()
    {
        var queryable = await _repository.WithDetailsAsync(x => x.Children);

        var entities = await queryable.AsNoTracking().ToListAsync();

        var menuDtos = ObjectMapper.Map<List<Menu>, List<MenuDto>>(entities);
        foreach (var item in menuDtos)
        {
            if (item.ParentId != Guid.Empty)
                item.ParentTitle = entities.First(x => x.Id == item.ParentId).Title;
        }
        return menuDtos;
    }

    /// <summary>
    /// 更新菜单信息
    /// </summary>
    /// <param name="menuEditDto"></param>
    /// <returns></returns>
    public async Task UpdateAsync(MenuEditDto menuEditDto)
    {
        var model = await _repository.GetAsync(x => x.Id == menuEditDto.Id);
        model.Title = menuEditDto.Title;
        model.ViewName = menuEditDto.ViewName;
        model.Icon = (PackIconKind)menuEditDto.Icon;

        if (!string.IsNullOrEmpty(menuEditDto.ViewName))
        {
            var menu = await _repository.GetAsync(x => x.Title == menuEditDto.ParentTitle);
            model.Parent = menu;
        }

        await _repository.UpdateAsync(model);
    }
}